import { useState, useEffect } from 'react';
import SearchBar from '@/components/SearchBar';
import RoleInfo from '@/components/RoleInfo';
import VoiceChat from '@/components/VoiceChat';
import { roles } from '@/mocks/roles';

interface HomeProps {
  selectedRole: any;
  setSelectedRole: (role: any) => void;
}

export default function Home({ selectedRole, setSelectedRole }: HomeProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [showResults, setShowResults] = useState(false);

  useEffect(() => {
    if (!selectedRole && roles.length > 0) {
      setSelectedRole(roles[0]);
    }
  }, [selectedRole, setSelectedRole]);

  const handleSearch = (query: string) => {
    setSearchQuery(query);
    if (query.length > 0) {
      const results = roles.filter(role => 
        role.name.toLowerCase().includes(query.toLowerCase()) || 
        role.description.toLowerCase().includes(query.toLowerCase())
      );
      setSearchResults(results);
      setShowResults(true);
    } else {
      setShowResults(false);
    }
  };

  const handleRoleSelect = (role: any) => {
    setSelectedRole(role);
    setShowResults(false);
    setSearchQuery('');
  };

  return (
    <div className="space-y-8">
      <section className="text-center mb-12">
        <h1 className="text-[clamp(2rem,5vw,3.5rem)] font-bold text-blue-700 mb-4">AI角色扮演</h1>
        <p className="text-gray-600 max-w-2xl mx-auto">与AI驱动的角色进行逼真对话，体验沉浸式的角色扮演体验</p>
      </section>

      <div className="max-w-4xl mx-auto">
        <SearchBar 
          query={searchQuery} 
          onChange={handleSearch} 
          results={searchResults}
          showResults={showResults}
          onRoleSelect={handleRoleSelect}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mt-10">
        {selectedRole && (
          <div className="lg:col-span-1">
            <RoleInfo role={selectedRole} />
          </div>
        )}
        
        <div className={`${selectedRole ? 'lg:col-span-2' : 'lg:col-span-3'} mt-8 lg:mt-0`}>
          <VoiceChat selectedRole={selectedRole} />
        </div>
      </div>
    </div>
  );
}